#!/usr/bin/perl
# 2013/06/03 Merge exp1 and exp2 map files

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;



if(@ARGV != 6 or $ARGV[0] eq '--help'){
	die "Usage : $0 -a [map file 1] -b [map file 2] -o [merged map file]\n";
}

my %opt;
getopts("a:b:o:", \%opt);
my $FILE_exp1 = $opt{a};
my $FILE_exp2 = $opt{b};
my $FILE_mix = $opt{o};

my %num = (
	'chr1'	=> 100000000,
	'chr2'	=> 200000000,
	'chr3'	=> 300000000,
	'I'	=> 100000000,
	'II'	=> 200000000,
	'III'	=> 300000000,
	'MT'	=> 400000000,
	'MTR'	=> 500000000,
	'AB325691'	=> 600000000,
	'NA'	=> 700000000
);




my $fh_exp1 = IO::File->new($FILE_exp1) or die "cannot open $FILE_exp1: $!";
my $fh_exp2 = IO::File->new($FILE_exp2) or die "cannot open $FILE_exp2: $!";
my $fh_out = IO::File->new($FILE_mix, 'w') or die "cannot write $FILE_mix: $!";

my $s1 = $fh_exp1->getline();
my $s2 = $fh_exp2->getline();

while($s1 && $s2){
	my $n1 = &calcValue($s1);
	my $n2 = &calcValue($s2);
	if($n1 < $n2){
		$fh_out->print("$s1");
		$s1 = $fh_exp1->getline();
	}elsif($n1 > $n2){
		$fh_out->print("$s2");
		$s2 = $fh_exp2->getline();
	}else{
		$fh_out->print("$s1");
		$fh_out->print("$s2");
		$s1 = $fh_exp1->getline();
		$s2 = $fh_exp2->getline();
	}
}
while($s1){
	$fh_out->print("$s1");
	$s1 = $fh_exp1->getline();
}
while($s2){
	$fh_out->print("$s2");
	$s2 = $fh_exp2->getline();
}
$fh_exp1->close();
$fh_exp2->close();
$fh_out->close();



sub calcValue{
	my ($data) = @_;
	my ($id, $chr1, $loc1, $direction1, $mapQ1, $hinID1, $hinLoc1, $chr2, $loc2, $direction2, $mapQ2, $hinID2, $hinLoc2, $type, $num, $locations) = split /\t/, $data;
	my $value1 = $num{$chr1} + $loc1;
	my $value2 = $num{$chr2} + $loc2;
	my $value = $value1 * 1000000000 + $value2;
	return $value;
}
